package com.caiyi.financial.nirvana.sms.server;

import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.CMPPStreamDecoder;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.CMPPStreamEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * cmpp服务端
 */
public class CmppServer extends Thread {
    private static final Logger logger = LoggerFactory.getLogger(CmppServer.class);
    private final int port;
    private ChannelFuture channelFuture = null;

    public CmppServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new CmppServer(7891).run();
    }

    public void run() {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 长度解码器
                            pipeline.addLast("length field decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
                            // 解码器
                            pipeline.addLast("decoder", new CMPPStreamDecoder());
                            // 编码器
                            pipeline.addLast("encoder", new CMPPStreamEncoder());
                            pipeline.addLast("idleCheck", new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS));
                            pipeline.addLast("receiver", new CmppServerHandler());
                            pipeline.addLast("controller", new CMPPServerControlHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 1024);

            channelFuture = b.bind().sync();
            logger.info(CmppServer.class.getName() + " started and listen on " + port);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("start error ", e);
        }
    }

}
